package com.hm.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hm.reggie.common.BaseContext;
import com.hm.reggie.common.R;
import com.hm.reggie.entity.ShoppingCart;
import com.hm.reggie.entity.User;
import com.hm.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/shoppingCart")
@Slf4j
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Transactional
    @GetMapping("/list")
    public R<List<ShoppingCart>> getList(HttpSession session){
        User user = (User)session.getAttribute("user");
        Long userId = user.getId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        queryWrapper.orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    /***
     * http://localhost:8080/shoppingCart/add   +   JSON格式的ShoppingCart对象
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session){
        User user = (User) session.getAttribute("user");
        log.info("当前用户是：{}。获取到前端的菜品信息：{}",user.getId(),shoppingCart);
        shoppingCart.setUserId(user.getId());
        LambdaQueryWrapper<ShoppingCart> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,user.getId());
        //判断添加的是菜品还是套餐
        if (shoppingCart.getDishId() != null) {
            //是菜品
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
        } else {
            //是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
        }
        //判断当前用户是否添加了相同菜品相同口味，如果相同则把数量+1
        int count = shoppingCartService.count(queryWrapper);
        if (count >= 1){
            //有相同的套餐或者菜品，数量+1
            ShoppingCart shoppingCart1 = shoppingCartService.getOne(queryWrapper);
            shoppingCart1.setNumber(shoppingCart1.getNumber()+1);
            boolean b = shoppingCartService.updateById(shoppingCart1);
            shoppingCart = shoppingCart1;
        } else if (count == 0) {
            //没有相同的，直接插入
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            boolean save = shoppingCartService.save(shoppingCart);
        } else {
            //异常
            log.error("有菜品或套餐重复添加了！！！");
        }


        log.info("保存到数据库后的菜品信息：{}",shoppingCart);
        return R.success(shoppingCart);
    }

    /***
     * 前端数据：JSON：：：{dishId: "1397851668262465537"}
     * 接受方法：直接Map，或者ShoppingCart对象也行
     *
     * 删除购物车菜品或者套餐
     * @param
     * @param session
     * @return
     */
//    @PostMapping("/sub")
//    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart,HttpSession session){
//        User user = (User)session.getAttribute("user");
//        Long userId = user.getId();
//        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(userId != null,ShoppingCart::getUserId,userId);
//        //判断是否是菜品和套餐
//        if (shoppingCart.getDishId() != null){
//            //是菜品
//            queryWrapper.eq(ShoppingCart::getDishId,shoppingCart.getDishId());
//        } else if (shoppingCart.getSetmealId() != null) {
//            //是套餐
//            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());
//        } else {
//            log.error("异常！！！");
//        }
//
//        //查找看具体是删除还是-1
//        ShoppingCart shoppingCartOne = shoppingCartService.getOne(queryWrapper);
//        if (shoppingCartOne == null) {
//            log.error("没找到对应的菜品或者套餐，检查异常!!!");
//            return R.error(null);
//        } else if (shoppingCartOne.getNumber() == 1) {
//            //只有一个，直接删除
//            boolean b = shoppingCartService.removeById(shoppingCartOne.getId());
//            return R.success(null);
//        } else if (shoppingCartOne.getNumber() > 1) {
//            //把数量-1
//            shoppingCartOne.setNumber(shoppingCartOne.getNumber() -1);
//            shoppingCartService.updateById(shoppingCartOne);
//        } else {
//            log.error("都没了还隔着-1呢");
//            return R.error(null);
//        }
//
//        return R.success(shoppingCartService.getOne(queryWrapper));
//    }
    /**
     * 客户端的套餐或者是菜品数量减少设置
     * 没必要设置返回值
     * @param shoppingCart
     */
    @PostMapping("/sub")
    @Transactional
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart,HttpSession session){
        User user = (User) session.getAttribute("user");

        Long dishId = shoppingCart.getDishId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();

        //代表数量减少的是菜品数量
        if (dishId != null){
            //通过dishId查出购物车对象
            queryWrapper.eq(ShoppingCart::getDishId,dishId);
            //这里必须要加两个条件，否则会出现用户互相修改对方与自己购物车中相同套餐或者是菜品的数量
            queryWrapper.eq(ShoppingCart::getUserId,user.getId());
            ShoppingCart cart1 = shoppingCartService.getOne(queryWrapper);
            cart1.setNumber(cart1.getNumber()-1);
            Integer LatestNumber = cart1.getNumber();
            if (LatestNumber > 0){
                //对数据进行更新操作
                shoppingCartService.updateById(cart1);
            }else if(LatestNumber == 0){
                //如果购物车的菜品数量减为0，那么就把菜品从购物车删除
                shoppingCartService.removeById(cart1.getId());
            }else if (LatestNumber < 0){
                return R.error("操作异常");
            }

            return R.success(cart1);
        }

        Long setmealId = shoppingCart.getSetmealId();
        if (setmealId != null){
            //代表是套餐数量减少
            queryWrapper.eq(ShoppingCart::getSetmealId,setmealId).eq(ShoppingCart::getUserId,user.getId());
            ShoppingCart cart2 = shoppingCartService.getOne(queryWrapper);
            cart2.setNumber(cart2.getNumber()-1);
            Integer LatestNumber = cart2.getNumber();
            if (LatestNumber > 0){
                //对数据进行更新操作
                shoppingCartService.updateById(cart2);
            }else if(LatestNumber == 0){
                //如果购物车的套餐数量减为0，那么就把套餐从购物车删除
                shoppingCartService.removeById(cart2.getId());
            }else if (LatestNumber < 0){
                return R.error("操作异常");
            }
            return R.success(cart2);
        }
        //如果两个大if判断都进不去
        return R.error("操作异常");
    }

    /***
     * http://localhost:8080/shoppingCart/clean
     * @return
     */
    @DeleteMapping("/clean")
    public R<String> deleteall(HttpSession session){
        Long currentId = BaseContext.getCurrentId();
        User user = (User)session.getAttribute("user");
        Long userId = user.getId();
        log.info("把用户{}的购物车清空",currentId);
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartService.remove(queryWrapper);
        return R.success("已全部删除");
    }
}
